package com.java.udp;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ClientSocket {

    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();
        ds.setSoTimeout(1000);
        Scanner scanner = new Scanner(System.in);
        // 指定服务器ip + port
        ds.connect(InetAddress.getByName("localhost"), 6666);
        while (true) {
            System.out.println("请输入你要发送的内容：");
            // 发送
            byte[] data = scanner.nextLine().getBytes(StandardCharsets.UTF_8);
            DatagramPacket packet = new DatagramPacket(data, data.length);
            ds.send(packet);

            // 接收
            byte[] buffer = new byte[1024];
            packet = new DatagramPacket(buffer, buffer.length);
            ds.receive(packet);
            String resp = new String(packet.getData(), packet.getOffset(), packet.getLength());
            System.out.println("服务端响应的内容：" + resp);
//            ds.disconnect();
        }
    }
}
